package com.tangkun.environment.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.activity.LoginActivity;
import com.tangkun.environment.activity.WuRanYuanActivity;
import com.tangkun.environment.activity.XiTongTongZhiActivity;
import com.tangkun.environment.activity.YiChangShuJuTiJaoActivity;
import com.tangkun.environment.adapter.FragmentAdapter;
import com.tangkun.environment.adapter.GongZuoGridViewAdapter;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.gongzuo.GongZuoBean;
import com.tangkun.environment.entity.gongzuo.WorkIndexReturn;
import com.tangkun.environment.entity.token.LoginReturn;
import com.tangkun.environment.fragment.BaseFragment;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxFragmentHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CircleImageView;
import com.tangkun.environment.view.CircleProgress;
import com.tangkun.environment.view.CommonDialog;
import com.tangkun.environment.view.IndicatorView;
import com.tangkun.environment.view.MyGridView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 工作Fragment
 */

public class Main2Fragment extends BaseFragment {

    @BindView(R.id.circleprogress)
    CircleProgress circleprogress;
    @BindView(R.id.tv_main_wancheng_percent)
    TextView tvMainWanchengPercent;
    @BindView(R.id.tv_main_wancheng_status)
    TextView tvMainWanchengStatus;
    @BindView(R.id.tv_main_jiedao)
    TextView tvMainJiedao;
    @BindView(R.id.ll_main_jiedao)
    LinearLayout llMainJiedao;
    @BindView(R.id.tv_main_shequ)
    TextView tvMainShequ;
    @BindView(R.id.ll_main_shequ)
    LinearLayout llMainShequ;
    @BindView(R.id.tv_main_weizhi)
    TextView tvMainWeizhi;
    @BindView(R.id.ll_main_weizhi)
    LinearLayout llMainWeizhi;
    @BindView(R.id.ll_main_fuzeren)
    LinearLayout llMainFuzeren;
    @BindView(R.id.tv_main_wuye)
    TextView tvMainWuye;
    @BindView(R.id.ll_main_wuye)
    LinearLayout llMainWuye;
    @BindView(R.id.tv_main_mingcheng)
    TextView tvMainMingcheng;
    @BindView(R.id.ll_main_mingcheng)
    LinearLayout llMainMingcheng;
    @BindView(R.id.tv_main_fuzeren_name)
    TextView tvMainFuzerenName;
    @BindView(R.id.tv_main_fuzeren_tel)
    TextView tvMainFuzerenTel;
    @BindView(R.id.view_mian2_mask)
    View viewMask;
    @BindView(R.id.civ_main_photo)
    CircleImageView civMainPhoto;
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;
    @BindView(R.id.iv_main_message)
    ImageView ivMainMessage;
    @BindView(R.id.iv_main_message_unread)
    ImageView ivMainMessageUnread;
    @BindView(R.id.rl_main_message)
    RelativeLayout rlMainMessage;
    @BindView(R.id.ll_main_shenhe_status)
    LinearLayout llMainShenheStatus;
    @BindView(R.id.tv_main_shenhe_daishen)
    TextView tvMainShenheDaishen;
    @BindView(R.id.tv_main_shenhe_yishen)
    TextView tvMainShenheYishen;
    @BindView(R.id.tv_main_shenhe_bohui)
    TextView tvMainShenheBohui;
    @BindView(R.id.ll_main_shenhe)
    LinearLayout llMainShenhe;
    @BindView(R.id.ll_main_quanbuwuranyuan)
    LinearLayout llMainQuanbuwuranyuan;
    @BindView(R.id.ll_main_fujinwuranyuan)
    LinearLayout llMainFujinwuranyuan;
    @BindView(R.id.ll_main_tongji)
    LinearLayout llMainTongji;
    @BindView(R.id.ll_main_yichangjubao)
    LinearLayout llMainYichangjubao;
    @BindView(R.id.ll_main_gengduogongneng)
    LinearLayout llMainGengduogongneng;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.indicatorView)
    IndicatorView indicatorView;
    @BindView(R.id.ll_main_not_qiyeyonghu)
    LinearLayout llMainNotQiyeyonghu;
    @BindView(R.id.rl_main_qiyeyonghu)
    RelativeLayout rlMainQiyeyonghu;
    @BindView(R.id.ll_main_tijiaoshuju)
    LinearLayout llMainTijiaoshuju;
    @BindView(R.id.mygridview)
    MyGridView myGridView;
    @BindView(R.id.rl_main_top)
    RelativeLayout rlMainTop;
    /*** Fragment+ViewPager ***/
    private ArrayList<Fragment> mFragmentList;
    private FragmentAdapter mFragmentAdapter;
    /**
     * Fragment选中项
     */
    private int mPosition = 0;
    /**
     * 企业用户数据源
     */
    private List<LoginReturn.UserInfo.BindlistBean> dataList = new ArrayList<LoginReturn.UserInfo.BindlistBean>();

    /**
     * GridView数据源
     */
    private List<GongZuoBean> dataListGridView = new ArrayList<GongZuoBean>();
    /**
     * GridView适配器
     */
    private GongZuoGridViewAdapter gridViewAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_main2, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        work();
        return view;
    }

    private void initData() {
        //顶部左上角头像
        Glide.with(getActivity())
                .load(GlobalUrl.IMG_URL + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(getActivity()))
                .placeholder(R.mipmap.ic_wrong_head)
                .dontAnimate()
                .into(civMainPhoto);

        if (!SharePrefercesUtils.getLoginStatus(getContext())) {//未登录用户
            viewMask.setVisibility(View.VISIBLE);//未登录，显示蒙层
            llMainNotQiyeyonghu.setVisibility(View.VISIBLE);
            rlMainQiyeyonghu.setVisibility(View.GONE);
            llMainShenheStatus.setVisibility(View.VISIBLE);

            llMainMingcheng.setVisibility(View.GONE);
            llMainJiedao.setVisibility(View.VISIBLE);
            llMainShequ.setVisibility(View.VISIBLE);
            llMainWeizhi.setVisibility(View.GONE);
            llMainFuzeren.setVisibility(View.GONE);
            llMainWuye.setVisibility(View.VISIBLE);

            initGridViewData();
        } else {//已登录用户
            //已经登录，不现显示蒙层
            viewMask.setVisibility(View.GONE);
            if (Session.getInstance().getUserRole().equals("企业用户")) {
                llMainNotQiyeyonghu.setVisibility(View.GONE);
                rlMainQiyeyonghu.setVisibility(View.VISIBLE);
                llMainShenheStatus.setVisibility(View.GONE);

                initFragment();
                initGridViewData();
            } else if (Session.getInstance().getUserRole().equals("街道巡查员")) {
                llMainNotQiyeyonghu.setVisibility(View.VISIBLE);
                rlMainQiyeyonghu.setVisibility(View.GONE);
                llMainShenheStatus.setVisibility(View.VISIBLE);

                llMainMingcheng.setVisibility(View.GONE);
                llMainJiedao.setVisibility(View.VISIBLE);
                llMainShequ.setVisibility(View.VISIBLE);
                llMainWeizhi.setVisibility(View.GONE);
                llMainFuzeren.setVisibility(View.GONE);
                llMainWuye.setVisibility(View.VISIBLE);

                initGridViewData();
            } else if (Session.getInstance().getUserRole().equals("协会巡查员")) {
                llMainNotQiyeyonghu.setVisibility(View.VISIBLE);
                rlMainQiyeyonghu.setVisibility(View.GONE);
                llMainShenheStatus.setVisibility(View.VISIBLE);

                llMainMingcheng.setVisibility(View.GONE);
                llMainJiedao.setVisibility(View.VISIBLE);
                llMainShequ.setVisibility(View.VISIBLE);
                llMainWeizhi.setVisibility(View.GONE);
                llMainFuzeren.setVisibility(View.GONE);
                llMainWuye.setVisibility(View.VISIBLE);

                initGridViewData();
            } else if (Session.getInstance().getUserRole().equals("监督员")) {
                llMainNotQiyeyonghu.setVisibility(View.VISIBLE);
                rlMainQiyeyonghu.setVisibility(View.GONE);
                llMainShenheStatus.setVisibility(View.VISIBLE);

                llMainMingcheng.setVisibility(View.GONE);
                llMainJiedao.setVisibility(View.VISIBLE);
                llMainShequ.setVisibility(View.VISIBLE);
                llMainWeizhi.setVisibility(View.GONE);
                llMainFuzeren.setVisibility(View.GONE);
                llMainWuye.setVisibility(View.VISIBLE);

                initGridViewData();
            }
        }
    }

    private void initGridViewData() {
        dataListGridView.clear();
        //0:全部污染源  1：附近污染源  2：提交数据  3：审核  4：举报异常  5：统计  6：更多
        GongZuoBean bean0 = new GongZuoBean();
        bean0.tag = 0;
        GongZuoBean bean1 = new GongZuoBean();
        bean1.tag = 1;
        GongZuoBean bean2 = new GongZuoBean();
        bean2.tag = 2;
        GongZuoBean bean3 = new GongZuoBean();
        bean3.tag = 3;
        GongZuoBean bean4 = new GongZuoBean();
        bean4.tag = 4;
        GongZuoBean bean5 = new GongZuoBean();
        bean5.tag = 5;
        GongZuoBean bean6 = new GongZuoBean();
        bean6.tag = 6;
        if (!SharePrefercesUtils.getLoginStatus(getContext())) {//未登录用户
            dataListGridView.add(bean0);
            dataListGridView.add(bean1);
            dataListGridView.add(bean2);
            dataListGridView.add(bean3);
            dataListGridView.add(bean4);
            dataListGridView.add(bean5);
            dataListGridView.add(bean6);
        } else {//已登录用户
            //0:全部污染源  1：附近污染源  2：提交数据  3：审核  4：举报异常  5：统计  6：更多
            if (Session.getInstance().getUserRole().equals("企业用户")) {
                dataListGridView.add(bean0);
                dataListGridView.add(bean1);
                dataListGridView.add(bean2);
                dataListGridView.add(bean6);
            } else if (Session.getInstance().getUserRole().equals("街道巡查员")) {
                dataListGridView.add(bean0);
                dataListGridView.add(bean1);
                dataListGridView.add(bean3);
                dataListGridView.add(bean4);
//                dataListGridView.add(bean5);
                dataListGridView.add(bean6);
            } else if (Session.getInstance().getUserRole().equals("协会巡查员")) {
                dataListGridView.add(bean0);
                dataListGridView.add(bean1);
                dataListGridView.add(bean3);
//                dataListGridView.add(bean5);
                dataListGridView.add(bean6);
            } else if (Session.getInstance().getUserRole().equals("监督员")) {
                dataListGridView.add(bean0);
                dataListGridView.add(bean1);
                dataListGridView.add(bean5);
                dataListGridView.add(bean4);
                dataListGridView.add(bean6);
            }
        }
        if (gridViewAdapter == null) {
            gridViewAdapter = new GongZuoGridViewAdapter(getActivity(), dataListGridView);
            //设置企业ID 用于提交数据时传递参数
            if (dataList != null && dataList.size() > 0) {
                gridViewAdapter.setEnterpriseid(dataList.get(0).ids);
            }
            myGridView.setAdapter(gridViewAdapter);
        } else {
            //设置企业ID 用于提交数据时传递参数
            if (dataList != null && dataList.size() > 0) {
                gridViewAdapter.setEnterpriseid(dataList.get(0).ids);
            }
            gridViewAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化fragment
     */
    private void initFragment() {
        mFragmentList = new ArrayList<Fragment>();
        dataList = Session.getInstance().getUserBindlist();
        //指示器的显示与隐藏
        if (dataList == null || dataList.size() <= 1) {
            indicatorView.setVisibility(View.INVISIBLE);
        } else {
            indicatorView.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < dataList.size(); i++) {
            Fragment fragment = new Main2ItemFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("index", i);
            fragment.setArguments(bundle);
            mFragmentList.add(fragment);
        }
        // tangkun:嵌套Fragment设置PageAdapter时要使用getChildFragmentManager,而不能使用getActivity().getSupportFragmentManager()
        mFragmentAdapter = new FragmentAdapter(getChildFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mFragmentAdapter);
        mFragmentAdapter.setFragments(mFragmentList);
        mViewPager.setOffscreenPageLimit(dataList.size());
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        mViewPager.setCurrentItem(mPosition);
        indicatorView.setViewPager(mViewPager);//指示器绑定viewpager
    }

    @Override
    public void onResume() {
        super.onResume();
        //顶部左上角头像
        Glide.with(getActivity())
                .load(GlobalUrl.IMG_URL + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(getActivity()))
                .placeholder(R.mipmap.ic_wrong_head)
                .dontAnimate()
                .into(civMainPhoto);
    }

    private void initView() {

    }

    /**
     * ViewPager监听事件
     */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(final int position) {
            mPosition = position;

            //设置企业ID 用于提交数据时传递参数
            String enterpriseid = dataList.get(position).ids;
            if (gridViewAdapter == null) {
                gridViewAdapter = new GongZuoGridViewAdapter(getActivity(), dataListGridView);
                gridViewAdapter.setEnterpriseid(enterpriseid);
                myGridView.setAdapter(gridViewAdapter);
            } else {
                gridViewAdapter.setEnterpriseid(enterpriseid);
                gridViewAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.view_mian2_mask, R.id.civ_main_photo, R.id.rl_main_message, R.id.ll_main_quanbuwuranyuan, R.id.ll_main_fujinwuranyuan, R.id.ll_main_tijiaoshuju, R.id.ll_main_shenhe, R.id.ll_main_tongji, R.id.ll_main_yichangjubao, R.id.ll_main_gengduogongneng})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_mian2_mask://页面上的蒙层，点击提示跳转登录对话框
                showLoginDialog();
                break;
            case R.id.civ_main_photo:
                EventBus.getDefault().post(true, "MainActivity.openDrawer");//发出通知给MainActivity，打开左抽屉
                break;
            case R.id.rl_main_message://顶部右上角消息 跳转系统通知
                JumpHelper.jump(getActivity(), XiTongTongZhiActivity.class, false);
                break;
            case R.id.ll_main_quanbuwuranyuan://全部污染源
                Intent quanbuwuranyuanIntent = new Intent(getActivity(), WuRanYuanActivity.class);
                quanbuwuranyuanIntent.putExtra("flag", 1);//全部污染源标识
                JumpHelper.jump(getActivity(), quanbuwuranyuanIntent, false);
                break;
            case R.id.ll_main_fujinwuranyuan://附近污染源
                Intent fujinwuranyuanIntent = new Intent(getActivity(), WuRanYuanActivity.class);
                fujinwuranyuanIntent.putExtra("flag", 2);//附近污染源标识
                JumpHelper.jump(getActivity(), fujinwuranyuanIntent, false);
                break;
            case R.id.ll_main_tijiaoshuju://提交数据
                break;
            case R.id.ll_main_shenhe://审核
                break;
            case R.id.ll_main_tongji://统计
                break;
            case R.id.ll_main_yichangjubao://异常举报
                JumpHelper.jump(getActivity(), YiChangShuJuTiJaoActivity.class, false);
                break;
            case R.id.ll_main_gengduogongneng://更多功能
                showToast("开发中");
                break;
        }
    }

    /**
     * 提示登录对话框
     */
    private void showLoginDialog() {
        CommonDialog commonDialog = new CommonDialog(getActivity(), "是否登录跳转", "您现在看到的是演示页面，登录后可使用功能，是否现在登录？", "否", "是");
        commonDialog.show();
        commonDialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void leftClick() {
                //否
            }

            @Override
            public void rightClick() {
                //是
                JumpHelper.jump(getActivity(), LoginActivity.class, true);
            }
        });
    }

    /**
     * 工作逻辑处理
     */
    private void work() {
        //已登录并且已绑定
        if (SharePrefercesUtils.getLoginStatus(getActivity())) {
            if (Session.getInstance().getUserRole().equals("企业用户")) {

            } else if (Session.getInstance().getUserRole().equals("街道巡查员")) {
                workIndex();
            } else if (Session.getInstance().getUserRole().equals("协会巡查员")) {
                workIndex();
            } else if (Session.getInstance().getUserRole().equals("监督员")) {
                workIndex();
            }
        }
    }

    /**
     * 工作数据
     */
    private void workIndex() {
        fromNetwork.workIndex().compose(new RxFragmentHelper<WorkIndexReturn>().ioMain(getActivity(), Main2Fragment.this, true))
                .subscribe(new MySubscribe<WorkIndexReturn>(getActivity(), true) {
                    @Override
                    protected void success(WorkIndexReturn resultBean) {
                        if (resultBean.data != null) {
                            //完成情况
                            tvMainWanchengPercent.setText(Utils.getOneDecimalPoint(resultBean.data.finishRate * 100) + "%");
                            circleprogress.reset();
                            circleprogress.clearAnimation();//清除动画试试
                            circleprogress.setValue(resultBean.data.finishRate * 100); //值
                            if (resultBean.data.finishRate == 1) {
                                tvMainWanchengStatus.setText("本月工作\n已完成");
                            } else {
                                tvMainWanchengStatus.setText("本月工作\n未完成");
                            }
                            //街道
                            String streetName = "";
                            if (resultBean.data.streetList != null) {
                                for (WorkIndexReturn.DataBean.StreetListBean bean : resultBean.data.streetList) {
                                    if (TextUtils.isEmpty(streetName)) {
                                        streetName = bean.names;
                                    } else {
                                        streetName = streetName + " " + bean.names;
                                    }

                                }
                            }
                            tvMainJiedao.setText(streetName + "");
                            //社区
                            String communityName = "";
                            if (resultBean.data.communityList != null) {
                                for (WorkIndexReturn.DataBean.CommunityListBean bean : resultBean.data.communityList) {
                                    if (TextUtils.isEmpty(communityName)) {
                                        communityName = bean.names;
                                    } else {
                                        communityName = communityName + " " + bean.names;
                                    }

                                }
                            }
                            tvMainShequ.setText(communityName + "");
                            //隐藏社区
                            llMainShequ.setVisibility(View.GONE);
                            //物业
                            String propertyName = "";
                            if (resultBean.data.propertyList != null) {
                                for (WorkIndexReturn.DataBean.PropertyListBean bean : resultBean.data.propertyList) {
                                    if (TextUtils.isEmpty(communityName)) {
                                        propertyName = bean.names;
                                    } else {
                                        propertyName = propertyName + " " + bean.names;
                                    }

                                }
                            }
                            tvMainWuye.setText(propertyName + "");
                            //待审
                            if (resultBean.data.inspectAuditNum > 0) {
                                tvMainShenheDaishen.setText(resultBean.data.inspectAuditNum + "");
                                tvMainShenheDaishen.setTextColor(getActivity().getResources().getColor(R.color.common_green));
                            } else {
                                tvMainShenheDaishen.setText("--");
                                tvMainShenheDaishen.setTextColor(getActivity().getResources().getColor(R.color.common_hint));
                            }
                            //已审
                            if (resultBean.data.finishNum > 0) {
                                tvMainShenheYishen.setText(resultBean.data.finishNum + "");
                                tvMainShenheYishen.setTextColor(getActivity().getResources().getColor(R.color.common_green));
                            } else {
                                tvMainShenheYishen.setText("--");
                                tvMainShenheYishen.setTextColor(getActivity().getResources().getColor(R.color.common_hint));
                            }
                            //驳回
                            if (resultBean.data.rejectNum > 0) {
                                tvMainShenheBohui.setText(resultBean.data.rejectNum + "");
                                tvMainShenheBohui.setTextColor(getActivity().getResources().getColor(R.color.common_green));
                            } else {
                                tvMainShenheBohui.setText("--");
                                tvMainShenheBohui.setTextColor(getActivity().getResources().getColor(R.color.common_hint));
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    @Subscriber(tag = "MainActivity.refreshFragment")
    private void refreshFragment(boolean flag) {
        initData();
        work();
    }
}
